<template>
  <div>
    <n-grid :x-gap="24">
      <n-grid-item span="5">
        <VoiceConfig :configJSON="localStoryCreatorConfig.voiceConfigText" ref="voiceConfigRef"></VoiceConfig>
      </n-grid-item>
      <n-grid-item span="19">
        <n-form :model="localStoryCreatorConfig" ref="formRef">
          <n-form-item label="绘画资源选择" path="resourceId">
            <n-select v-model:value="localStoryCreatorConfig.resourceId" :options="resourceOption"
                      @update:value="resourceSelect">
            </n-select>
            <n-tooltip>
              <template #trigger>
                <n-button type="primary" @click="loadConfig" style="margin-left:5px; ">刷新
                  <template #icon>
                    <n-icon>
                      <SyncCircleOutline/>
                    </n-icon>
                  </template>
                </n-button>
              </template>
              <span>刷新资源</span>
            </n-tooltip>
          </n-form-item>
        </n-form>
        <SdImg2Img ref="SdImg2ImgRef" v-if="selectedResourceOption?.type==='SD' && selectedResourceOption?.value"
                   :story="props.story" :resourceId="selectedResourceOption.value" :useProgrammeSetting="props.useProgramme"></SdImg2Img>

        <Fooocus ref="fooocusRef" v-if="selectedResourceOption?.type === 'Fooocus'"></Fooocus>

        <MjSetting ref="mjRef" v-if="selectedResourceOption?.type === 'MJ'"  ></MjSetting>

      </n-grid-item>
    </n-grid>
  </div>
</template>

<script setup lang="ts">
import {defineEmits, nextTick, onMounted, reactive, ref, watch} from 'vue';
import {useMessage} from 'naive-ui';
import {resourceController} from '@/api/resource/resourceController.api'
import {storyController} from '@/api/story/story.api'
// @ts-ignore
import fileFunction from "@/libs/globalFunction/file";
import SdImg2Img from '@/components/creator/boardConfig/sdImg2Img.vue'
import VoiceConfig from '@/components/creator/boardConfig/voiceConfig.vue'
import {SyncCircleOutline} from "@vicons/ionicons5";

import Fooocus from '@/views/pages/aiart/fooocus/index.vue'
import MjSetting from "@/views/pages/create/video/components/mjSetting_temp.vue";

const emit = defineEmits()
const resourceOption = ref([])
const selectedResource = ref("")
const selectedResourceOption = ref({
  label: '',
  value: '',
  type: ''
})
const formRef: any = ref(null);
const message = useMessage();
const voiceConfigRef = ref(null)
const SdImg2ImgRef = ref(null)
const fooocusRef = ref(null)
const mjRef = ref(null)

const props = defineProps({
  story: {
    type: Object,
    default: () => {
      return {}
    }
  },
  storyCreatorConfig: {
    type: Object,
    default: () => {
      return {}
    }
  },
  updateStoryCreatorConfig: {
    required: true,
    type: Function
  },
  useProgramme:{
    type:Boolean,
    default:true,
  }
})

const localStoryCreatorConfig = reactive(props.storyCreatorConfig)

watch(() => localStoryCreatorConfig, (val) => {
  console.log(localStoryCreatorConfig)
})

/***
 * 获取绘画资源
 */
const getResourceInfo = async () => {
  try {
    const res = await resourceController.getSDResource('ALL');
    if (res.code === 200) {
      res.data.forEach((item: any) => {
        // @ts-ignore
        resourceOption.value.push({
          label: item.resourceName,
          value: item.id,
          type: item.type,
        });
      })
    } else {
      message.error(res.msg);
    }
  } catch (error) {
    // 处理错误
    console.error(error);
  }
}

/**
 * 获取该章节的绘画配置
 * @param chapterId
 */
    // const getStoryPaintConfig = async (chapterId:string) =>{
    //   try{
    //     const res = await storyController.getStoryPaintConfig(chapterId);
    //     if(res.code === 200){
    //       if(res.data != null) {
    //         Object.assign(localStoryCreatorConfig, res.data)
    //         selectedResourceOption.value.type = res.data.paintType
    //         selectedResourceOption.value.value = res.data.resourceId
    //         loadConfig()
    //       }
    //     } else {
    //       message.error(res.msg);
    //     }
    //   }catch (error){
    //     console.error(error);
    //   }
    // }

const loadConfig = () => {
  nextTick(() => {
    let config = null
    if (localStoryCreatorConfig.paintConfigText != null && localStoryCreatorConfig.paintConfigText.length > 0) {
      config = localStoryCreatorConfig.paintConfigText
    }
    if(config!=null && config.length > 0){
      // 判断当前选中的资源是否和配置的资源一致
      if(selectedResourceOption.value.type != localStoryCreatorConfig.paintType || selectedResourceOption.value.value != localStoryCreatorConfig.resourceId){
        config = null;
      }
    }

    if (selectedResourceOption.value.type == 'SD') {
      SdImg2ImgRef.value?.loadConfig(config, selectedResourceOption.value.value)
    }
    if (selectedResourceOption.value.type == 'Fooocus') {
      fooocusRef.value?.loadConfig(config)
    }
    if (selectedResourceOption.value.type == 'MJ') {
      mjRef.value?.loadConfig(config)
    }
    if (localStoryCreatorConfig.voiceConfigText.length > 0) {
      voiceConfigRef.value?.loadConfig(localStoryCreatorConfig.voiceConfigText)
    }
  });
}

// 选中资源后
const resourceSelect = (value: string, option: any) => {
  selectedResource.value = value
  selectedResourceOption.value = option;
  loadConfig()
}


const saveStoryConfig = async (callback: any) => {
  let paintConfig = {}
  if (selectedResourceOption.value.type == 'SD') {
    paintConfig = await SdImg2ImgRef.value.getConfig()
  }else if (selectedResourceOption.value.type == 'Fooocus') {
    paintConfig = await fooocusRef.value.getConfig()
  }else if (selectedResourceOption.value.type == 'MJ') {
    paintConfig = await mjRef.value.getConfig()
  }

  console.log(paintConfig)

  const voiceConfig = await voiceConfigRef.value.getConfig()
  if (!voiceConfig || !paintConfig) {
    callback(false)
    return
  }
  localStoryCreatorConfig.paintType = selectedResourceOption.value.type
  localStoryCreatorConfig.resourceId = selectedResourceOption.value.value
  localStoryCreatorConfig.paintConfigText = JSON.stringify(paintConfig)
  localStoryCreatorConfig.voiceConfigText = JSON.stringify(voiceConfig)
  localStoryCreatorConfig.chapterId = props.story.id
  storyController.saveStoryConfig(localStoryCreatorConfig).then(res => {
    if (res.code === 200) {
      props.updateStoryCreatorConfig()
      message.success("保存成功")
      callback(true)
    } else {
      message.error(res.msg);
      callback(false)
    }
  })
}

onMounted(async () => {
  await getResourceInfo()
  selectedResourceOption.value.type = localStoryCreatorConfig.paintType
  selectedResourceOption.value.value = localStoryCreatorConfig.resourceId
  loadConfig()
})


defineExpose({
  saveStoryConfig
})
</script>
